<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Area;
use app\admin\model\Userfarm as UserfarmMdl;
use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

class Userfarm extends BaseController
{

    /**
     * 列表
     */
    public function getList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->uid)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'uid 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        //$userId = $param->userId;
        $where = [
            'userId' => $param->uid
        ];

        $model = new UserfarmMdl();
        $fields = '*';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        foreach ($result as $item) {
            $item['villageName'] = \app\admin\model\Villages::where('id', $item['villageId'])->value('name');
            $item['croptypeName'] = \app\admin\model\Croptype::where('id', $item['croptypeId'])->value('name');
            $item['cropName'] = \app\admin\model\Crop::where('id', $item['cropId'])->value('name');
            $item['varietieName'] = \app\admin\model\Varieties::where('id', $item['varietieId'])->value('name');

            // 图片
            $item['imgList'] = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserfarmMdl();
        $field = '*';
        $item = $model->where($where)->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关数据');
        }

        $item['villageName'] = \app\admin\model\Villages::where('id', $item['villageId'])->value('name');
        $item['croptypeName'] = \app\admin\model\Croptype::where('id', $item['croptypeId'])->value('name');
        $item['cropName'] = \app\admin\model\Crop::where('id', $item['cropId'])->value('name');
        $item['varietieName'] = \app\admin\model\Varieties::where('id', $item['varietieId'])->value('name');

        // 图片
        $item['imgList'] = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 保存
     */
    public function save()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->name)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '农场名称(name) 不能为空');
        }
        if (empty($param->croptypeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '农作物分类(croptypeId) 不能为空');
        }
        if (empty($param->cropId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '农作物(cropId) 不能为空');
        }
        /*if (empty($param->varietieId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '品种(varietieId) 不能为空');
        }*/
        if (empty($param->area)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '面积(area) 不能为空');
        }
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '所在地(villageId) 不能为空');
        }
        if (empty($param->address)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '详细地址(address) 不能为空');
        }

        $userId = $param->userId;

        Db::startTrans();
        try {
            $data = (array)$param;
            $model = new UserfarmMdl();

            $xianId = Area::where('id', $param->townId)->value('parentId');
            $cityId = Area::where('id', $xianId)->value('parentId');
            $data['cityId'] = $cityId;
            $data['xianId'] = $xianId;

            if (!empty($param->id)) {
                $id = $param->id;
                $data['updateDate'] = time();
                $data['userId'] = $userId;

                $result = $model->allowField(true)->save($data, ['id' => $id]);
            } else {
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();

                $result = $model->save($data);
            }

            if($result !== false){
                // 图片
                $res = '';
                if(isset($param->imgUrls) && $param->imgUrls) {
                    $imgUrls = (array) $param->imgUrls;
                    foreach($imgUrls as $key => $imgUrl){
                        $res = Image::where(['imgUrl' => $imgUrl])->update(['relatedId' => $data['id'], 'relatedTable' => 'userfarm', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '保存图片失败');
                }
                Db::commit();
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '保存失败', $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '保存失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 删除
     */
    public function delete()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserfarmMdl();
        $result = $model->where($where)->delete();
        if ($result === false) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
        }

        // Query执行后的操作
        $model->_after_delete($param->id);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /**
     * 选择农场
     */
    public function selectedFarm()
    {
        $param = self::getHttpParam();

        if (empty($param->farmId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'farmId 不能为空');
        }

        $where = [
            'a.id' => $param->farmId
        ];
        $model = new UserfarmMdl();
        $field = 'c.phenological, c.farmingProject';
        $item = $model->alias('a')->where($where)->join('__CROP__ c', 'a.cropId = c.id')->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关数据');
        }
        // 物候期
        $item['phenological'] = explode(',', $item['phenological']);
        // 农事项目
        $item['farmingProject'] = explode(',', $item['farmingProject']);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

}